package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil
import com.hankcs.hanlp.HanLP
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONArray
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 *
 * @Title: HST_Api_Translate
 * @Description:深圳华盛证券百度翻译接口--内部部接口
 * @author: chieh* @date 2021-09-08 21:16:00
 *
 */
public class HST_Api_Translate implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(HST_Api_Translate.class);

    private static String URL = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    private static String appid = "20211014000973000";
    private static String appSecret = "EeLlvedaJrNCwSfsLgeT";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        log.debug("-------------------------start HST_Api_Translate 开始-----------------");

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        JSONObject reJson = new JSONObject();
        JSONObject trans_result = new JSONObject();
        JSONArray trans_resultarr = new JSONArray();

        //获取参数js_code，登录时获取的 code
        def q = request.getParameter("q");
        def salt = request.getParameter("salt");
        def sign = request.getParameter("sign");
        def from = request.getParameter("from");
        def to = request.getParameter("to");
        String q1 = null;
        try {
            log.debug("q-1：" + q);
            // q1 = URLDecoder.decode(q, "UTF-8");
            q1 = URLDecoder.decode(q.replaceAll("%", "%25"), "UTF-8");
            log.debug("q1-1：" + q1);

			q1=q1.replaceAll("%","%25");
			q1=q1.replaceAll(" ","%20");
			q1=q1.replaceAll("/","%2F");
			q1=q1.replaceAll("?","%3F");
			q1=q1.replaceAll("#;","%23");
			q1=q1.replaceAll("&","%26");
			q1=q1.replaceAll("+","%2B");
			q1=q1.replaceAll("=","%3D");
			log.debug("q1-2：" + q1);

        } catch (Exception e) {
            log.warn("转义待翻译内容错误：" + e.getMessage());
            q1 = q;
        }
        log.debug("接收参数q：" + q + ",salt：" + salt + ",sign：" + sign + ",from：" + from + ",to：" + to + ",转义q：" + q1);

        try {
            reJson.put("from", from);
            reJson.put("to", to);
            trans_result.put("src", q);
            trans_result.put("dst", q);

            if ((from == "zh" && to == "zh") || (from == "cht" && to == "cht") || (from == "en" && to == "en")) {
                reJson.put("resdesc", "源语言和目标语言类型一致,无需翻译-跳过!");
                trans_resultarr.put(trans_result);
                reJson.put("trans_result", trans_resultarr);
                log.warn("翻译处理结果：" + reJson.toString());
                return reJson;

            }

            if (from == null || to == null) {
                reJson.put("resdesc", "源语言和目标语言类型存在空,无法完成翻译!");
                trans_resultarr.put(trans_result);
                reJson.put("trans_result", trans_resultarr);
                log.warn("翻译处理结果：" + reJson.toString());
                return reJson;
            }

            String src = "";
            String dst = "";
            //繁体语则单字拆分
            if ((from == "zh" || from == "auto") && to == "cht") {
                reJson.put("resdesc", "zh|auto->cht");
                src = q1;
                dst = HanLP.convertToTraditionalChinese(q1);
				dst=dst.replaceAll("%25","%");
				dst=dst.replaceAll("%20"," ");
				dst=dst.replaceAll("%2F","/");
				dst=dst.replaceAll("%3F","?");
				dst=dst.replaceAll("%23","#;");
				dst=dst.replaceAll("%26","&");
				dst=dst.replaceAll("%2B","+");
				dst=dst.replaceAll("%3D","=");
				log.debug("dst-1：" + dst);

            } else if ((from == "cht" || from == "auto") && to == "zh") {
                reJson.put("resdesc", "cht|auto->zh");
                src = q1;
                dst = HanLP.convertToSimplifiedChinese(q1);
				dst=dst.replaceAll("%25","%");
				dst=dst.replaceAll("%20"," ");
				dst=dst.replaceAll("%2F","/");
				dst=dst.replaceAll("%3F","?");
				dst=dst.replaceAll("%23","#;");
				dst=dst.replaceAll("%26","&");
				dst=dst.replaceAll("%2B","+");
				dst=dst.replaceAll("%3D","=");
				log.debug("dst-2：" + dst);

            } else {
                String Translateresult = getTranslate(q1, salt, from, to, sign);
                JSONObject transObject = new JSONObject(Translateresult);
                reJson.put("resdesc", Translateresult);
                src = KHUtil.GetJV(transObject, "src");
                dst = KHUtil.GetJV(transObject, "dst");

            }

            long endTime = System.currentTimeMillis();
            log.debug("耗时：" + (endTime - startTime));

            trans_result.put("src", src);
            trans_result.put("dst", dst);
            trans_resultarr.put(trans_result);
            reJson.put("trans_result", trans_resultarr);

        } catch (Exception e) {
            log.error("接口处理异常", e);
            reJson.put("from", from);
            reJson.put("to", to);
            reJson.put("resdesc", "接口处理异常：" + e.getMessage());
            trans_result.put("src", q);
            trans_result.put("dst", q);
            trans_resultarr.put(trans_result);
            reJson.put("trans_result", trans_resultarr);
        }
        log.debug("翻译处理结果：" + reJson.toString());
        return reJson.toString();

    }

    //调度百度api翻译
    public static String getTranslate(String q1, String salt, String from, String to, String sign) {

        String src, dst, desc;
        try {
            //String getParam = "q=" + q1 + "&salt=" + salt + "&appid=" + appid + "&sign=" + sign + "&from=" + from + "&to=" + to;
            //String doURL = URL + "?" + URLEncoder.encode(getParam, "utf-8");
            
			String getParam = "q=" + URLEncoder.encode(q1, "utf-8") + "&salt=" + salt + "&appid=" + appid + "&sign=" + sign + "&from=" + from + "&to=" + to;
            String doURL = URL + "?" + getParam;

            String getResult = Util.doHttpGet(doURL, "UTF-8", 10000, 0);
            log.warn("调动百度翻译调用结果:" + getResult);

            if (!KHUtil.isNull(getResult)) {
                JSONObject transObject = new JSONObject(getResult);

                String trans_result = KHUtil.GetJV(transObject, "trans_result");
                log.debug("调动百度翻译trans_result:" + trans_result);

                JSONArray resArray = new JSONArray(trans_result);
                log.debug("调动百度翻译resArray:" + resArray);

                src = resArray.getJSONObject(0).get("src");
                dst = resArray.getJSONObject(0).get("dst");

                log.debug("调动百度翻译src：" + src + "，	dst：" + dst);

            } else {
                desc = "调动百度翻译返回结果空！";
                src = q1;
                dst = q1;
            }
        } catch (Exception e) {
            log.warn("调动百度翻译错误！", e);
            desc = "调动百度翻译错误！" + e.getMessage();
            src = q1;
            dst = q1;
        }
        JSONObject result = new JSONObject();
        result.put("desc", desc);
        result.put("src", src);
        result.put("dst", dst);
        return result.toString();
    }
}